<template>
    <!-- 计算字段脚本编辑 -->
    <el-form labelWidth="120px" class="mt-4" :model="model" ref="formRef">
        <el-form-item label="脚本类型" prop="scriptType">
            <el-radio-group v-model="model.scriptType" :disabled="!editing" @change="scriptTypeChanged">
                <el-radio-button label="表达式" value="ognl" />
                <el-radio-button label="JS脚本" value="javascript" />
                <el-radio-button label="groovy脚本" value="groovy" />
            </el-radio-group>
        </el-form-item>

        <el-form-item label="表达式" :required="true" v-if="model.scriptType == 'ognl'" prop="script">
            <el-input type="textarea" v-model="model.script" placeholder="请输入表达式内容" :rows="10" :disabled="!editing" />
            <div class="remark">
                表达式示例：
                <li>计算：field_a + field_b * field_c + 100</li>
                <li>条件：field_a + field_b > 100</li>
                <li>三元运算：field_a > 10 ? field_b : field_c</li>
            </div>
        </el-form-item>

        <el-form-item :label="model.scriptType == 'javascript' ? 'JS脚本' : 'Groovy脚本'" v-else :required="true" prop="script">
            <monacoEditor height="320px" v-model="model.script" language="javascript" v-if="model.scriptType == 'javascript'"
                :readonly="!editing" />
            <monacoEditor height="320px" v-model="model.script" language="groovy" v-else :readonly="!editing" />
        </el-form-item>
    </el-form>
</template>
<script setup>
    import monacoEditor from '@/components/monaco-editor.vue'

    const model = defineModel()
    const formRef = ref()
    const props = defineProps({
        editing: Boolean
    })
    const defJs = `function func(value, lastValue = {}) {
    // value为当前设备上传过来的记录，lastValue为上一条记录，上一条记录有可能为空，注意区分
    return 1;
}`

    const defGroovy = `def func(value, lastValue = [:]) {
    // value为当前设备上传过来的记录，lastValue为上一条记录，上一条记录有可能为空，注意区分
    return 1
}`

    function validate(callback) {
        formRef.value.validate(callback)
    }

    function scriptTypeChanged(val) {
        if (model.value.script) {
            return
        }

        let script 
        if (val == 'ognl') {
            script = ''
        } else if (val == 'javascript') {
            script = defJs
        } else if (val == 'groovy') {
            script = defGroovy
        }

        model.value.script = script
    }

    defineExpose({
        validate
    })
</script>

<style lang='scss' scoped></style>